import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui';
import axios from 'axios'
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false

Vue.prototype.$axios = axios

const instance = axios.create({
  baseURL: "http://localhost:3000/",
  timeout: 3000,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
})
Vue.use(ElementUI);

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

instance.defaults.headers.post['Content-Type'] = 'application/json';

// http request 请求拦截器
instance.interceptors.request.use(
  config => {
    config.headers.AcceptLanguage = getLocalStorage("locale");
    if (localStorage.jwtToken) {
      config.headers.Authorization = getLocalStorage("jwtToken");
    }
    console.log('config', config);
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
// http response 响应拦截器
instance.interceptors.response.use(
  response => {
    console.log('response', response);
    return handleData(response.data)
  },
  error => {
    if (error.response.data.status === 500 && (error.response.data.message === 'token out time' || error.response.data.message === '登录失败或未登录')) {
      setLocalStorage('jwtToken');
      window.location.href = baseUrl.url1;
    }
    let err = error.response.data.message;
    if (err != '' && err != null && err != undefined) {
      Message({
        type: 'error',
        message: error.response.data.message
      })
      return Promise.reject(error.response.data)
    } else {
      Message({
        type: 'error',
        message: 'HTTP:服务器遇到错误,无法完成请求。'
      })
    }
  }
)
const errorHandle = (status, other) => {
  // 状态码判断
  switch (status) {
    // 401: 未登录状态，跳转登录页   
    case 401:
      toLogin();
      break;
    // 403 token过期
    // 清除token并跳转登录页
    case 403:
      tip('登录过期，请重新登录');
      localStorage.removeItem('token');
      store.commit('loginSuccess', null);
      setTimeout(() => {
        toLogin();
      }, 1000);
      break;
    // 404请求不存在
    case 404:
      tip('请求的资源不存在');
      break;
    default:
      console.log(other);
  }
}
